﻿using Dapper;
using HDLogCenter.Infrastructure.Models;
using HDLogCenter.Infrastructure.Mysql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HDLogCenter.Dal.Repos
{
    public class AlertRuleRepo
    {
        private readonly IDbService _dbService;

        public AlertRuleRepo(IDbService dbService)
        {
            _dbService = dbService;
        }

        public async Task<IEnumerable<AlertRuleModel>> GetAllAsync()
        {
            using (var connection = _dbService.GetConnection())
            {
                return await connection.GetListAsync<AlertRuleModel>();
            }
        }

        public async Task<AlertRuleModel> GetByIdAsync(long id)
        {
            using (var connection = _dbService.GetConnection())
            {
                return await connection.GetAsync<AlertRuleModel>(id);
            }
        }

        public async Task<IEnumerable<AlertRuleModel>> GetByAppCodeAsync(string appCode)
        {
            using (var connection = _dbService.GetConnection())
            {
                var result = await connection.GetListAsync<AlertRuleModel>(new { ProjectCode = appCode });
                return result;
            }
        }

        public async Task<int?> CreateAsync(AlertRuleModel alertRule)
        {
            using (var connection = _dbService.GetConnection())
            {
                alertRule.CreateTime = DateTime.Now;
                alertRule.UpdateTime = DateTime.Now;
                return await connection.InsertAsync(alertRule);
            }
        }

        public async Task<bool> UpdateAsync(AlertRuleModel alertRule)
        {
            using (var connection = _dbService.GetConnection())
            {
                alertRule.UpdateTime = DateTime.Now;
                var result = await connection.UpdateAsync(alertRule);
                return result > 0;
            }
        }

        public async Task<bool> DeleteAsync(long id)
        {
            using (var connection = _dbService.GetConnection())
            {
                var result = await connection.DeleteAsync<AlertRuleModel>(id);
                return result > 0;
            }
        }
    }
}